<template>
  <div class="app-container">
    <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"
             style="margin-top: 20px">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-tag color="#2b85e4" style="color:white;margin-left:10px;margin-bottom:20px" size="large">
            登录信息
          </el-tag>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                <el-input v-model="formData.username" class="user-info-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="密码" prop="password" :label-width="formLabelWidth" v-if="actionType=='add'">
                <el-input type="password" v-model="formData.password" class="user-info-input"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="70" style="margin-top:10px">
            <el-col :span="12">
              <el-form-item label="确认密码" prop="comfirmPassword" :label-width="formLabelWidth" v-if="actionType=='add'">
                <el-input type="password" v-model="formData.comfirmPassword" class="user-info-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-tag color="#2b85e4" style="color:white;margin-left:10px;margin-bottom:20px" size="large">
            用户信息
          </el-tag>
          <el-row :gutter="30">
            <el-col :span="12">
              <el-form-item label="所属组织" :label-width="formLabelWidth" prop="organizationId">
                <el-select v-model="formData.organizationIds" placeholder="请选择" no-data-text="暂无数据"
                           class="user-info-input" multiple>
                  <el-option
                    v-for="item in allData"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="姓名" prop="name" :label-width="formLabelWidth">
                <el-input v-model="formData.name" class="user-info-input"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="30" style="margin-top:10px">
            <el-col :span="12">
              <el-form-item label="手机号码" prop="telphone" :label-width="formLabelWidth">
                <el-input v-model="formData.telphone" class="user-info-input"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" :label-width="formLabelWidth">
                <el-radio-group v-model="formData.sex">
                  <el-radio label="1">男</el-radio>
                  <el-radio label="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <image-cropper :width="300" :height="300" :url="uploadUrl" @close='close'
                         @crop-upload-success="cropSuccess" langType="zh"
                         :key="imagecropperKey" v-show="imagecropperShow"
                         field="file"></image-cropper>
          <el-row type="flex" justify="center" style="margin-top:30px">
            <el-col :span="6">
              <pan-thumb :image="baseUrl+formData.headimgUrl"></pan-thumb>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center" style="margin-top:15px">
            <el-col :span="1">
              <el-button type="primary" icon="upload" style=""
                         @click="imagecropperShow=true">上传头像
              </el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row type="flex" justify="left">
        <el-col :span="12" style="margin-top: 20px">
          <el-form-item>
            <el-button type="success" @click="handleAdd('ruleForm')" v-if="actionType=='add'" :loading="loading">立即创建
            </el-button>
            <el-button type="success" @click="handleEdit('ruleForm')" v-else :loading="loading">修改</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<style scoped>
  .user-info-input {
    width: 200px;
  }

  .avatar {
    width: 200px;
    height: 200px;
    border-radius: 50%;
  }
</style>

<script>
  import organizationApi from '@/api/organizationApi'
  import userApi from '@/api/userApi'
  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  import {isValidPassword} from '@/common/validate'

  export default {
    components: {ImageCropper, PanThumb},
    created() {
      if (this.actionType == 'add') {
        this.listAllOrganization()
      } else {
        organizationApi.listAllOrganization({}, (res) => {
          this.allData = res
          this.getData()
        }, () => {
        })
      }
    },
    data() {
      const validatePassword = (rule, value, callback) => {
        if (this.formData.password != '' && this.formData.comfirmPassword) {
          if (!isValidPassword(this.formData.password, this.formData.comfirmPassword)) {
            callback(new Error('密码输入不一致'))
          } else {
            callback()
          }
        }
      }
      return {
        baseUrl: process.env.IMG_BASE_URL,
        actionType: this.$route.params.type,
        updateId: this.$route.query.id,
        allData: [],
        uploadUrl: process.env.BASE_API + '/admin/user/upload',
        imagecropperShow: false,
        imagecropperKey: 0,
        formLabelWidth: '80px',
        comfirmPassword: '',
        formData: {
          username: '',
          password: '',
          comfirmPassword: '',
          name: '',
          sex: '1',
          telphone: '',
          headimgUrl: '/default.jpg',
          organizationIds: []
        },
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur'},
            {trigger: 'blur', validator: validatePassword},
          ],
          comfirmPassword: [
            {required: true, message: '请输入确认密码', trigger: 'blur'},
            {min: 6, max: 50, message: '长度在 6 到 50 个字符', trigger: 'blur'},
            {trigger: 'blur', validator: validatePassword},
          ],
          organizationIds: [
            {required: true, message: '请选择组织', trigger: 'change'}
          ],
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'}
          ],
          telphone: [
            {required: true, message: '请输入手机号码', trigger: 'blur'}
          ]
        },
        loading: false
      };
    },
    methods: {
      listAllOrganization() {
        organizationApi.listAllOrganization({}, (res) => {
          this.allData = res
        }, () => {
        })
      }
      ,
      handleAdd(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //this.loading = true
            userApi.addUser(this.formData, (res) => {
              this.loading = false
              this.$message({
                message: '添加成功',
                type: 'success',
              })
              this.$router.replace({path: '/system/user/list'})
            }, () => {
              //this.loading = false
            })
          } else {
            return false;
          }
        })
      },
      getData() {
        userApi.getUserById(this.updateId, (res) => {
          this.formData = res
        }, () => {
        })
      },
      handleEdit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true
            userApi.updateUser(this.updateId, this.formData, (res) => {
              this.loading = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
            }, () => {
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      cropSuccess(resData) {
        this.imagecropperShow = false
        this.imagecropperKey = this.imagecropperKey + 1
        this.formData.headimgUrl = resData
      },
      close() {
        this.imagecropperShow = false
      }
    }
  }
</script>
